package cn.angis.generate.builder;

import cn.angis.generate.util.ExtractFieldFnUtil;
import org.beetl.core.Template;
import org.beetl.sql.gen.Attribute;
import org.beetl.sql.gen.BaseProject;
import org.beetl.sql.gen.Entity;
import org.beetl.sql.gen.SourceConfig;
import org.beetl.sql.gen.simple.BaseTemplateSourceBuilder;

import java.io.Writer;
import java.util.ArrayList;

public class DtoOutputBuilder extends BaseTemplateSourceBuilder {
    public static String pojoPath = "dtoOutput.html";
    private String module;

    public DtoOutputBuilder() {
        super("dto.output");
    }

    public DtoOutputBuilder(String module) {
        super("dto.output");
        this.module = module;
    }

    public void generate(BaseProject project, SourceConfig config, Entity entity) {
        Template template = groupTemplate.getTemplate(pojoPath);

        // 注册方法
        groupTemplate.registerFunction("extractField", new ExtractFieldFnUtil());

        template.binding("module", this.module);
        template.binding("attrs", entity.getList());
        template.binding("className", entity.getName());
        template.binding("table", entity.getTableName());
        if (!config.isIgnoreDbCatalog()) {
            template.binding("catalog", entity.getCatalog());
        }

        template.binding("package", project.getBasePackage(this.name));
        template.binding("imports", entity.getImportPackage());
        template.binding("colsMap", entity.getTableDesc().getColsDetail());
        template.binding("comment", entity.getComment());

        ArrayList<Attribute> attrList = entity.getList();
        boolean hasLogicDel = attrList.stream().anyMatch(p -> "isDeleted".equals(p.getName()));
        template.binding("hasLogicDel", hasLogicDel);

        Writer writer = project.getWriterByName(this.name, entity.getName() + "Output.java");
        template.renderTo(writer);
    }
}
